﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Data.OleDb;
using System.Data.SQLite;
using System.IO;
using Tesseract;
using System.Xml.Linq;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Threading;
using laicigoujiaoyi.Model;
using static laicigoujiaoyi.Model.DogAttributes;
using Microsoft.VisualBasic;
using System.Diagnostics;
using System.Xml;
using System.Web;
using System.Data.SqlClient;

namespace laicigoujiaoyi
{
    public partial class Form1 : Form
    {
        bool isrunning = false;
        bool Pagesbool = true;
        bool threadbool = false;
        int Pages = 1;
        int threadnum = 1;
        string cookie = "";
        string cha = "";
        string seed = "";
        string newseed = "";
        string puimg = "";
        static string papa = Application.StartupPath;
<<<<<<< HEAD
        List<string> Dogconde=null;

=======
        static List<string> AllDogList = null;
     //   static string dbPath =  papa + "\\laicigou.db";
>>>>>>> origin/master
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 加载配置
        /// </summary>
        public void GetConfigure()
        {
            try
            {
                // string papa = Application.StartupPath;
                XDocument document = XDocument.Load(papa + "\\Configure.xml");
                //获取到XML的根元素进行操作
                XElement root = document.Root;
                //XElement ele = root.Element("BDUSS");
                IEnumerable<XElement> enumerable = root.Elements();
                foreach (XElement item in enumerable)
                {
                    if (item.Name == "common")
                    {
                        DogPrice.Getcommon = item.Value.ToString();
                        textBox1.Text = DogPrice.Getcommon;
                    }
                    else if (item.Name == "rare")
                    {
                        DogPrice.Getrare = item.Value.ToString();
                        textBox2.Text = DogPrice.Getrare;
                    }
                    else if (item.Name == "excellence")
                    {
                        DogPrice.Getexcellence = item.Value.ToString();
                        textBox3.Text = DogPrice.Getexcellence;

                    }
                    else if (item.Name == "epic")
                    {
                        DogPrice.Getepic = item.Value.ToString();
                        textBox4.Text = DogPrice.Getepic;

                    }
                    else if (item.Name == "mythical")
                    {
                        DogPrice.Getmythical = item.Value.ToString();
                        textBox5.Text = DogPrice.Getmythical;

                    }
                    else if (item.Name == "Legend")
                    {
                        DogPrice.GetLegend = item.Value.ToString();
                        textBox10.Text = DogPrice.GetLegend;

                    }
                    else if (item.Name == "interval")
                    {
                        DogPrice.Getinterval = Convert.ToInt32(item.Value);
                        textBox6.Text = item.Value.ToString();
                    }

                    else if (item.Name == "minimum")
                    {
                        DogPrice.Getminimum = Convert.ToInt32(item.Value);
                        textBox11.Text = item.Value.ToString();
                    }
                    else if (item.Name == "pages")
                    {
                        DogPrice.Getpages = Convert.ToInt32(item.Value);
                        comboBox3.Text = item.Value.ToString();
                    }


                }

            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 加载百度cookie
        /// </summary>
        public void GetcookieTXT(string cookitxml)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(papa + "\\Cookie.xml");//加载xml文件，文件
                XmlNode xns = xmlDoc.SelectSingleNode("Cookie");//查找要修改的节点
                XmlNodeList xnl = xns.ChildNodes;//取出所有的子节点
               comboBox4.Items.Clear();
                foreach (XmlNode xn in xnl)
                {
                    XmlElement xe = (XmlElement)xn;//将节点转换一下类型
                    if (xe.Name == cookitxml)//判断该子节点是否是要查找的节点
                    {
                        //获取name标签的值
                        textBox13.Text = xe.InnerText.ToString();
                        comboBox4.Text = cookitxml;
                        cookie = xe.InnerText.ToString();
                       
                    }
                    else
                    {
                        comboBox4.Text = "选择不到用户请登陆获取";
                    }

                    comboBox4.Items.Add(xe.Name);
                }
              
            }
            catch (Exception)
            {
                comboBox4.Text = "选择不到用户请登陆获取";
                // throw;
            }
      
        }
        /// <summary>
        /// 开始启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            //this.comboBox4 .DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
          this.toolStripComboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
          //   toolStripComboBox2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;  
            GetcookieTXT(comboBox4.Text );       
            GetConfigure();
         
        }





        /// <summary>
        /// 开始刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        /// <summary>  
        /// 将json数据转换成实体类     
        /// </summary>  
        /// <returns></returns>  
        private static List<Postdata.PetsOnSaleItem> getObjectByJson(string jsonString)
        {
            // 实例化DataContractJsonSerializer对象，需要待序列化的对象类型  
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Postdata.PetsOnSaleItem>));
            //把Json传入内存流中保存  
            jsonString = "[" + jsonString + "]";
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            // 使用ReadObject方法反序列化成对象  
            object ob = serializer.ReadObject(stream);
            List<Postdata.PetsOnSaleItem> ls = (List<Postdata.PetsOnSaleItem>)ob;
            return ls;
        }
        /// <summary>
        /// 判断价格是否比配置少
        /// </summary>
        /// <param name="rareDegree"></param>
        /// <param name="amount"></param>
        /// <param name="petid"></param>
        /// <param name="vcode"></param>
        public bool GetContrast(string rareDegree, string amount, string petid, string vcode)
        {
            bool Com = false;
            if (rareDegree.ToString().Trim() == "普通" && (Convert.ToDouble(DogPrice.Getcommon) >= Convert.ToDouble(amount)))
            {
                textBox7.Text += rareDegree + ": " + amount + "\r\n";
                // Putdogg(petid, amount, vcode,"","");
            }
            else if (rareDegree == "稀有" && (Convert.ToDouble(DogPrice.Getrare) >= Convert.ToDouble(amount)))
            {
                textBox7.Text += rareDegree + ": " + amount + "\r\n";
                //    Putdogg(petid, amount, vcode, "", "");
            }
            else if (rareDegree == "卓越" && (Convert.ToDouble(DogPrice.Getexcellence) >= Convert.ToDouble(amount)))
            {
                textBox7.Text += rareDegree + ": " + amount + "\r\n";
                // Putdogg(petid, amount, vcode, "", "");
            }
            else if (rareDegree == "神话" && (Convert.ToDouble(DogPrice.Getmythical) >= Convert.ToDouble(amount)))
            {
                textBox7.Text += rareDegree + ": " + amount + "\r\n";
                // Putdogg(petid, amount, vcode, "", "");
            }
            else if (rareDegree == "传说" && (Convert.ToDouble(DogPrice.GetLegend) >= Convert.ToDouble(amount)))
            {
                textBox7.Text += rareDegree + ": " + amount + "\r\n";
                //   Putdogg(petid, amount, vcode, "", "");
            }
            else
            {
                Com = true;
            }
            return Com;

        }
        /// <summary>
        /// 直接购买
        /// </summary>
        /// <param name="petid"></param>
        /// <param name="price_str"></param>
        /// <param name="vcode">validCode</param>
        /// <param name="seedaa"></param>
        /// <param name="chaaa"></param>
        public void Putdogg(string petid, string price_str, string vcode, string seed, string cha)
        {
            if (!string.IsNullOrEmpty(textBox9.Text))
            {
                try
                {

                    string str = textBox9.Text;
                    str = str.Replace("\r\n", "\n");
                    string[] strArr = str.Split('\n');
                    string[] temp1 = strArr[0].ToString().Split(',');
                    seed = temp1[1].ToString();
                    cha = temp1[0].ToString();
                    string text = "";
                    for (int i = 1; i < strArr.Length; i++)
                    {
                        text += strArr[i] + (i == strArr.Length - 1 ? "" : "\r\n"); //最后一行不添加换行符
                    }
                    textBox9.Text = text;
                }
                catch (Exception)
                {

                   // throw;
                }
            }
            ExtenModel.Getseedaa = seed;
            ExtenModel.Getchaaa = cha;
            ExtenModel.Getpetid = petid;
            ExtenModel.Getprice_str = price_str;
            ExtenModel.Getvcode = vcode;
            GetCodeForm getform = new GetCodeForm();
            getform.ShowDialog();
        }
        /// <summary>
        /// 获取排序规则
        /// </summary>
        /// <returns></returns>
        public string Getsort()
        {
            // RAREDEGREE_DESC 稀有度高 RAREDEGREE_ASC 稀有度低编码低 ，AMOUNT_ASC价格低， AMOUNT_DESC 价格高 CREATETIME_ASC
            string ret = "";
            string a = toolStripComboBox2.Text;
            if (a == "价格最低")
            {
                ret = "AMOUNT_ASC";
            }
            else if (a == "价格最高")
            {
                ret = "AMOUNT_DESC";
            }
            else if (a == "稀有度最低")
            {
                ret = "RAREDEGREE_ASC";
            }
            else if (a == "稀有度最高")
            {
                ret = "RAREDEGREE_DESC";
            }
            else if (a == "创建时间早")
            {
                ret = "CREATETIME_ASC";
            }
            else if (a == "创建时间晚")
            {
                ret = "CREATETIME_DESC";
            }
            return ret;
        }
        /// <summary>
        /// 根据界面配置获取价格
        /// </summary>
        public void GetDogpr()
        {
            string ret = "";
            string a = toolStripComboBox1.Text;
            if (a == "所有狗狗")
            {
                ret = "allprices";
            }
            else if (a == "普通")
            {
                ret = DogPrice.Getcommon;
            }
            else if (a == "稀有")
            {
                ret = DogPrice.Getrare;
            }
            else if (a == "卓越")
            {
                ret = DogPrice.Getexcellence;
            }
            else if (a == "史诗")
            {
                ret = DogPrice.Getepic;
            }
            else if (a == "神话")
            {
                ret = DogPrice.Getmythical;
            }
            else if (a == "传说")
            {
                ret = DogPrice.GetLegend;
            }
        }
        /// <summary>
        /// 实时刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {

            Thread thread = new Thread(GetDog);
            if (Pagesbool)
            {
                lock (this)
                {
                    thread.Start();//
                                   //  GetDog();
                }
            }
            if (threadbool)
            {
                thread.Abort();
                // thread.Join();
                timer1.Stop();
            }
        }
        /// <summary>
        /// 单次请求
        /// </summary>
        public void GetDog()
        {
            Pagesbool = false;
            string ret = "";
            int pagesnum = 1;
            try
            {
                if (isrunning)
                {
                    pagesnum = DogPrice.Getpages;
                }
                listView1.Items.Clear();
                for (int iaa = 0; iaa < pagesnum; iaa++)
                {
                    Pages = iaa + 1;
                    if (threadbool)
                    {
                        Pages = 1;
                        break;
                    }
                    label12.Text = "第" + (iaa + 1).ToString() + "页";
                    ret = Dog.queryPetsOnSale((iaa + 1).ToString(), "20", Getsort());
                    JObject res_j = (JObject)JsonConvert.DeserializeObject(ret);
                    JArray res_ja = (JArray)res_j["data"]["petsOnSale"];
                    JObject apet = (JObject)res_ja[0];
                    string apettt = res_ja.ToString();
                    var arry = JsonConvert.DeserializeObject<object[]>(apettt);
                    // Thread.Sleep(DogPrice.Getinterval);
                    if (checkBox5.Checked ==false  )
                    {
                        listView1.Items.Clear();
                    }
                    textBox7.Text = "";
                    string petid = (string)apet["petId"];
                    string vcode = (string)apet["validCode"];
                    string price_str = (string)apet["amount"];
                    string birthType = Convert.ToString(apet["birthType"]);
<<<<<<< HEAD
                    if (Dogconde  .Contains(petid))
                        return;

=======

                    if (ExtenModel.Getccodedog.Contains (petid))
                    {
                        return;
                    }
>>>>>>> origin/master
                    for (var i = 0; i < arry.Length; i++)
                    {
                        List<AttributesItem> attri = new List<AttributesItem>();
                        StringBuilder DograreDegree = new StringBuilder();//稀有
                        StringBuilder DograreDegreep = new StringBuilder();//稀有
                        Postdata.PetsOnSaleItem PostOnSaleItem = (Postdata.PetsOnSaleItem)JsonConvert.DeserializeObject(arry[i].ToString(), typeof(Postdata.PetsOnSaleItem));
                        string petby = Dog.queryPetById(PostOnSaleItem.petId);
                        JObject petby_j = (JObject)JsonConvert.DeserializeObject(petby);
                        string petby_ja = (string)petby_j["data"].ToString();
                        AttributesData petby_OnSaleItem = (AttributesData)JsonConvert.DeserializeObject(petby_ja.ToString(), typeof(AttributesData));

                        if (!GetContrast(petby_OnSaleItem.rareDegree.ToString(), petby_OnSaleItem.amount.ToString(), petid, vcode))
                        {
                           
                            Putdogg(petid, petby_OnSaleItem.amount.ToString(), vcode, "", "");
                            Dogconde.Add(petid);
                            Getuser();

                            //GetContrast(petby_OnSaleItem.rareDegree.ToString(), petby_OnSaleItem.amount.ToString(), petid, vcode);
                        }
                        else
                        {
                            if (checkBox4.Checked != true)
                            {
                                for (int ia = 0; ia < petby_OnSaleItem.attributes.Count; ia++)
                                {
                                    //属性
                                    if (petby_OnSaleItem.attributes[ia].rareDegree == "稀有")
                                    {
                                        DograreDegree.Append(petby_OnSaleItem.attributes[ia].name + ":" + petby_OnSaleItem.attributes[ia].value + ",  ");
                                    }
                                    else
                                    {
                                        DograreDegreep.Append(petby_OnSaleItem.attributes[ia].name + ":" + petby_OnSaleItem.attributes[ia].value + ",  ");
                                    }
                                }
                               
                                    if (checkBox6.Checked == true)
                                    {
                                        GetUrlsq(petby_OnSaleItem.id.ToString(),
                        petby_OnSaleItem.amount.ToString(), petby_OnSaleItem.rareDegree.ToString(), petby_OnSaleItem.petId.ToString()
                        , DograreDegree.ToString(), DograreDegreep.ToString(), PostOnSaleItem.validCode, petby_OnSaleItem.userName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                                    } 
                              

                                if (toolStripComboBox1.Text == petby_OnSaleItem.rareDegree.ToString() || toolStripComboBox1.Text == "所有狗狗")
                                {
                                    this.listView1.BeginUpdate();
                                    listView1.Items.Add(new ListViewItem(new string[] { petby_OnSaleItem.id.ToString(),
                        petby_OnSaleItem .amount.ToString(), petby_OnSaleItem .rareDegree.ToString(), petby_OnSaleItem .petId .ToString()
                        ,DograreDegree.ToString (),DograreDegreep.ToString (),PostOnSaleItem.validCode,petby_OnSaleItem.userName}));
                                    this.listView1.EndUpdate();
                                }
                               
                            }
                        }




                    }
                }

            }
            catch (Exception)
            {
            }
            Pagesbool = true;
        }
        public string dogImage()
        {
            string a = "";
            try
            {
                string ret = Dog.getCha();
                JObject res_j = (JObject)JsonConvert.DeserializeObject(ret);
                newseed = (string)res_j["data"]["seed"];
                string img = (string)res_j["data"]["img"];
                puimg = img;
                a = newseed;
                pictureBox2.Image = Dog.str2Image(img);
            }
            catch (Exception) { }
            return a;
        }
        /// <summary>
        /// 回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_cha_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && textBox_cha.Text.Length == 4)
            {
                try
                {
                    dogImage();
                }
                catch (Exception ex)
                {

                }
            }
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        public void Getuser()
        {
            try
            {
                string ret = Dog.showUser();
                JObject res_j = (JObject)JsonConvert.DeserializeObject(ret);
                string u_name = (string)res_j["data"]["userName"];
                string u_amount = (string)res_j["data"]["amount"];
                toolStripTextBox1.Text = "微积分：" + u_amount;
                toolStripTextBox2.Text = "用户名：" + u_name;
            }
            catch (Exception)
            {


            }

        }
        /// <summary>
        /// 获取订单信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void GetOaderlist()
        {
            try
            {
                string ret = Dog.getMyOrder();
                JObject res_j = (JObject)JsonConvert.DeserializeObject(ret);
                JArray res_ja = (JArray)res_j["data"]["dataList"];
                listView2.Items.Clear();
                for (int i = 0; i < res_ja.Count; i++)
                {
                    JObject apet = (JObject)res_ja[i];
                    string amount = (string)apet["amount"];
                    int status = (int)apet["status"];//1 卖出 2买入
                    int txnstatus = (int)apet["txnStatus"];//状态 1上链中 
                    string txnstatusstr = txnstatus == 1 ? "上链中" : txnstatus.ToString();
                    string statusstr = (status == 1 ? "卖出" : "买入");
                    string id = (string)apet["id"];//
                    string petId = (string)apet["petId"];//
                    string petName = (string)apet["petName"];//
                    string transDate = (string)apet["transDate"];//
                    string fee = (string)apet["fee"];//   
                    string svgPath = (string)apet["svgPath"];//
                    string bgColor = (string)apet["bgColor"];//
                    this.listView2.BeginUpdate();
                    listView2.Items.Add(new ListViewItem(new string[] { id.ToString(),
                    petId,petName,transDate,amount,fee,txnstatusstr,statusstr,svgPath,bgColor}));
                    this.listView2.EndUpdate();
                }
            }
            catch (Exception)
            {


            }
        }
        /// <summary>
        /// 获取自己狗狗链表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void GetMylist()
        {
            try
            {
                string ret = Dog.GetMyDoglist();
                JObject res_j = (JObject)JsonConvert.DeserializeObject(ret);
                JArray res_ja = (JArray)res_j["data"]["dataList"];
                listView3.Items.Clear();
                for (int i = 0; i < res_ja.Count; i++)
                {
                    JObject apet = (JObject)res_ja[i];
                    string petId = (string)apet["petId"];
                    //    int status = (int)apet["status"];//1 卖出 2买入
                    double amount = (double)apet["amount"];
                    string buyingstate = "正常";
                    //   int txnstatus = (int)apet["txnStatus"];//状态 1上链中 
                    string petby = Dog.queryPetById(petId);
                    JObject petby_j = (JObject)JsonConvert.DeserializeObject(petby);
                    string petby_ja = (string)petby_j["data"].ToString();
                    AttributesData petby_OnSaleItem = (AttributesData)JsonConvert.DeserializeObject(petby_ja.ToString(), typeof(AttributesData));
                    StringBuilder DograreDegree = new StringBuilder();
                    StringBuilder DograreDegreep = new StringBuilder();

                    for (int ia = 0; ia < petby_OnSaleItem.attributes.Count; ia++)
                    {
                        //属性
                        if (petby_OnSaleItem.attributes[ia].rareDegree == "稀有")
                        {
                            DograreDegree.Append(petby_OnSaleItem.attributes[ia].name + ":" + petby_OnSaleItem.attributes[ia].value + ",  ");
                        }
                        else
                        {
                            DograreDegreep.Append(petby_OnSaleItem.attributes[ia].name + ":" + petby_OnSaleItem.attributes[ia].value + ",  ");
                        }
                    }
                    if (amount > 0.00)
                    {
                        buyingstate = "卖出中";
                    }
                    this.listView3.BeginUpdate();
                    listView3.Items.Add(new ListViewItem(new string[] { petby_OnSaleItem.id.ToString(),
                        petby_OnSaleItem .amount.ToString(), petby_OnSaleItem .rareDegree.ToString(), petby_OnSaleItem .petId .ToString()
                        ,DograreDegree.ToString (),DograreDegreep.ToString (),buyingstate}));

                    this.listView3.EndUpdate();
                }
            }
            catch (Exception)
            {

            }
        }

      

        public static  bool  Geturlupdate(string idname, string amount, string rareDegree, string petId, string DograreDegree, string DograreDegreep, string validCode, string userName, string datetime)
        {
            bool sqlsum = false;
            string dbPath = "Data Source =" + papa + "\\laicigou.db";
            try
            {
                SQLiteConnection conn = null;
                string sql = "update nameurl set amount='" + (amount) + "',rareDegree='" + (rareDegree) + "',DograreDegree=" +
                         "'" + (DograreDegree) + "',DograreDegreep='" + (DograreDegreep) + "',validCode='" + (validCode) + "',userName='" + (userName) + "',datetime='" + (datetime) + "' where idname =  '" + (idname) + "' and petId='" + (petId) + "' ";
                conn = new SQLiteConnection(dbPath);//创建数据库实例，指定文件位置  
                conn.Open();
                SQLiteCommand command = new SQLiteCommand(sql, conn);
                // command.ExecuteNonQuery();
              //  cmd.CommandText = sql;
              //  cmd.ExecuteNonQuery();
                if (command.ExecuteNonQuery() >0)
                {
                    sqlsum = true;
                }
                conn.Close();
            }
            catch (Exception)
            {
                sqlsum = false;

                // throw;
            }
            return sqlsum;
        }

        public  string GetUrlsq(string idname, string amount, string rareDegree, string petId, string DograreDegree, string DograreDegreep, string validCode, string userName,string datetime)
        {
            string dbPath =  papa + "\\laicigou.db";
            string rolename = "";
            if (AllDogList.Contains("petid"))
            {
                if (checkBox7.Checked ==true )
                {
                if (Getnameselect(idname))
                {
                    Geturlupdate(idname.ToString(),
                        amount.ToString(), rareDegree.ToString(), petId.ToString()
                        , DograreDegree.ToString(), DograreDegreep.ToString(), validCode, userName, datetime);
                }
                }
            }
            else
            {
                SQLiteConnection conn = null;
                conn = new SQLiteConnection("Data Source =" + dbPath);//创建数据库实例，指定文件位置  
                try
                {
                    if (!File.Exists(dbPath))
                    {
                        conn.Open();//打开数据库，若文件不存在会自动创建  
                        string sql = "CREATE TABLE IF NOT EXISTS nameurl(id integer PRIMARY KEY AUTOINCREMENT , idname varchar(250)," +
                    " amount varchar(250), rareDegree varchar(250)," +
                    " petId varchar(250), DograreDegree varchar(250)," +
                    " DograreDegreep varchar(250), validCode varchar(250), userName varchar(250), datetime varchar(250))";//建表语句  
                                                                                                                          //  SQLiteCommand cmdCreateTable = new SQLiteCommand(sql, conn);
                        SQLiteDBHelper db = new SQLiteDBHelper(dbPath);
                        // cmdCreateTable.ExecuteNonQuery();//如果表不存在，创建数据表   
                        db.ExecuteNonQuery(sql, null);
                        conn.Close();
                    }
                    conn.Open();//打开数据库，若文件不存在会自动创建  
                    SQLiteCommand cmdInsert = new SQLiteCommand(conn);
                    cmdInsert.CommandText = @"INSERT INTO nameurl (idname,amount,rareDegree,petId,DograreDegree
                     ,DograreDegreep,validCode,userName,datetime) VALUES( '" + (idname) + "','" + (amount) + "','" + (rareDegree) + "','" + (petId) + "'," +
                     "'" + (DograreDegree) + "','" + (DograreDegreep) + "','" + (validCode) + "','" + (userName) + "','" + (datetime) + "')";//插入几条数据  
                    cmdInsert.ExecuteNonQuery();
                    AllDogList.Add(idname);
                    conn.Close();
                }
                catch (Exception e)
                {
                    Gettxt(papa, DateTime.Now.ToString() + "  插入语句报错 " + e.Message.ToString() + "\r\n");
                }
            }
            return rolename;
        }
        /// <summary>
        /// /使用sql查询语句，并显示结果
        /// </summary>
        static bool  Getnameselect(string idname)
        {
            bool wselect=false ;
            try
            {
                string dbPath = papa + "\\laicigou.db";
                SQLiteConnection conn = null;
                string sql = "select * from nameurl where idname=" + idname;
                SQLiteDBHelper db = new SQLiteDBHelper(dbPath);
                using (SQLiteDataReader reader = db.ExecuteReader(sql, null))
                {
                    while (reader.Read())
                    {
                        if (reader["idname"].ToString() == idname)
                        {
                            wselect = true;
                        }
                    }
                }

            }
            catch (Exception)
            {

                
            }
            return wselect;
        }


        public static void Gettxt(string path, string content)
        {
            //  FileInfo fi = new FileInfo(filename);
            string aas = path + "\\" + DateTime.Parse(DateTime.Now.ToString()).ToString("yyyy-MM-dd") + ".txt";
            FileStream fsa = new FileStream(aas, FileMode.Append);
            StreamWriter swa = new StreamWriter(fsa);
            swa.WriteLine(content);
            swa.Flush();
            swa.Close();
            fsa.Close();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //推这次的参数上去
                cha = textBox_cha.Text.Trim();
                seed = newseed;
                //拿下次的码&显示，seed存newseed   
                string ret = "";
                if (checkBox1.Checked == true)
                {
                    ret = Dog.getgift(seed, cha, "", Convert.ToInt32(comboBox1.Text), comboBox2.Text);
                }
                else
                {
                    ret = Dog.getgift(seed, cha, "601123f4999a5086", Convert.ToInt32(comboBox1.Text), comboBox2.Text);
                }
                JObject res_j = (JObject)JsonConvert.DeserializeObject(ret);
                //MessageBox.Show(ret); {{  "errorNo": "20005",  "errorMsg": "狗狗正在生产中,请稍后再领",  "timestamp": "2018-02-25 13:11:44",  "data": null}}
                string data = (string)res_j["data"];
                if (string.IsNullOrEmpty(data))
                {
                    string errorNo = (string)res_j["errorNo"];
                    string errorMsg = (string)res_j["errorMsg"];
                    label_chaused.Text = errorNo + errorMsg;
                    if (errorNo != "100")
                    {
                       // GetUrlsq(cha, puimg);
                    }

                }
                else
                {
                    MessageBox.Show(ret.ToString());
                }
                dogImage();

                //清空自己
                textBox_cha.Clear();
                //  label_chaused.Text = "new cha";
                label_chaused.ForeColor = Color.Green;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

        }
        private void textBox_cha_TextChanged(object sender, EventArgs e)
        {
            if (textBox_cha.Text.Length == 4 && checkBox1.Checked == true)
            {
                button1_Click(null, null);
            }
        }
        public string StartOCR(Image numImage)
        {
            string txt = "";
            string defaultList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            const string language = "eng";

            //Nuget安装的Tessract版本为3.02，tessdata的版本必须与其匹配，另外路径最后必须以"\"或者"/"结尾
            // const string TessractData = @"K:\Working\百度莱茨狗\1.1\laicigoujiaoyi\bin\Debug\";
            const string TessractData = @"K:\Working\百度莱茨狗\1.1\laicigoujiaoyi\bin\Debug\";

            Tesseract.TesseractEngine test = new Tesseract.TesseractEngine(TessractData, language);

            test.SetVariable("tessedit_char_whitelist", defaultList);

            Bitmap tmpVal = (Bitmap)numImage;
            Page tmpPage = test.Process(tmpVal, pageSegMode: test.DefaultPageSegMode);

            txt = tmpPage.GetText();


            return txt;
        }
        private void 获取CookieToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GetCookie getcoo = new GetCookie();
            getcoo.Show();
        }
        private void 开始查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
<<<<<<< HEAD
            Dogconde  = new List<string>();
=======
            ExtenModel.Getccodedog = new List<string>();
>>>>>>> origin/master
            if (string.IsNullOrEmpty(toolStripComboBox1.Text) && string.IsNullOrEmpty(toolStripComboBox2.Text))
            {
                MessageBox.Show("还没有选择需要抢购的狗狗品质和 规则");
            }
            else
            {

           
            isrunning = !isrunning;
            Pages = 1;
            if (isrunning)
            {
                threadbool = false;
                开始查询ToolStripMenuItem.Text = "停止抢狗模式";
                timer1.Interval = DogPrice.Getinterval;
                timer1.Start();
            }
            else
            {
                threadbool = true;
                开始查询ToolStripMenuItem.Text = "开始抢狗模式";


                }
            }
        }
        /// <summary>
        /// 保存配置
        /// </summary>
        public void Saveconfiguration()
        {
            try
            {
                //获取根节点对象
                XDocument document = new XDocument();
                XElement root = new XElement("Cookie");
                //  XElement book = new XElement("BOOK");
                root.SetElementValue("common", textBox1.Text);
                root.SetElementValue("rare", textBox2.Text);
                root.SetElementValue("excellence", textBox3.Text);
                root.SetElementValue("epic", textBox4.Text);
                root.SetElementValue("mythical", textBox5.Text);
                root.SetElementValue("Legend", textBox10.Text);
                root.SetElementValue("interval", textBox6.Text);
                root.SetElementValue("minimum", textBox11.Text);
                root.SetElementValue("pages", comboBox3.Text);
                root.Save(papa + "\\Configure.xml");

            }
            catch (Exception)
            {
                MessageBox.Show("保存错误");

            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            if (!string .IsNullOrEmpty (textBox13.Text ))
            {
                Saveconfiguration();
                GetConfigure();
                Dog.GetCookieva = cookie;
             
                dogImage();
                Getuser();
                GetOaderlist();
                GetMylist();
                MessageBox.Show("保存成功"); 
            }
            else
            {
                MessageBox.Show("请选择登陆用户");
            }

           
        }
        private void button5_Click(object sender, EventArgs e)
        {
            Dog.queryPetById("1922974231292584223");
        }
        static bool toolmen=false ;
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
<<<<<<< HEAD
            Dogconde = new List<string>();
=======
            ExtenModel.Getccodedog = new List<string>();
>>>>>>> origin/master
            if (string.IsNullOrEmpty(toolStripComboBox1.Text) && string.IsNullOrEmpty(toolStripComboBox2.Text))
            {
                MessageBox.Show("还没有选择需要抢购的狗狗品质和 规则");
            }
            else
            {
            toolmen = !toolmen;
            Pages = 1;
            Thread thread = new Thread(GetDog);     //执行的必须是无返回值的方法
            if (toolmen)
            {
                threadbool = false;
                thread.Start();
                threadnum++;
                toolStripMenuItem1.Text = "终止稳定模式";

            }
            else
            {
                thread.Abort();
                toolStripMenuItem1.Text = "开始稳定模式";


            }
            }


        }
        List<string> GetCode = new List<string>();
        int CodeNum = 0;
        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            if (textBox8.Text.Length == 4 && checkBox3.Checked == true)
            {
                GetCode.Add(textBox8.Text + "," + newseed);

                textBox9.Text += (textBox8.Text.ToString().Trim() + "," + newseed.ToString().Trim() + "\r\n");
                CodeNum++;
                dogImage();
                textBox8.Text = "";
            }
        }
        private void button6_Click(object sender, EventArgs e)
        {
            GetCodeForm aa = new GetCodeForm();
            aa.ShowDialog();
        }
        private void button4_Click_1(object sender, EventArgs e)
        {
            textBox9.Text = "";
        }
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem myItem = new ListViewItem();
                myItem = listView1.SelectedItems[0];//获取选中行  
                ExtenModel.Getpetid = myItem.SubItems[3].Text;
                ExtenModel.Getprice_str = myItem.SubItems[1].Text;
                ExtenModel.Getvcode = myItem.SubItems[6].Text;
            }
        }
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            // Dog.buyPet(listpet, listvcode, listprice,"","");
            Putdogg(ExtenModel.Getpetid, ExtenModel.Getprice_str, ExtenModel.Getvcode, "", "");
            GetOaderlist();
        }

        private void listView3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView3.SelectedItems.Count > 0)
            {
                ListViewItem myItem = new ListViewItem();
                myItem = listView3.SelectedItems[0];//获取选中行  
                ExtenModel.Getpetid = myItem.SubItems[3].Text;
            }
        }
        private void 取消买卖ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string str = Dog.GetunsalePet(ExtenModel.Getpetid);
         //   JObject res_j = (JObject)JsonConvert.DeserializeObject(str);
            MessageBox.Show(Dog.GeterrorMsg(str));
        }

        private void 卖出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {

                int input = Convert.ToInt32(Interaction.InputBox("你喜欢填写多少就多少，建议整数", "请填写卖出价格", "8888", -1, -1));

                if (input > DogPrice.Getminimum)
                {
                    string ret=    Dog.GetsalePet(ExtenModel.Getpetid, input.ToString());
                    MessageBox.Show(Dog.GeterrorMsg(ret));
                    // GetOaderlist();
                    GetMylist();
                }
                else
                {
                    MessageBox.Show("低于最低分，不可卖出，请修改最低分");
                }
            }
            catch (Exception)
            {
            }
        }
        private void button7_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox12.Text))
            {
                string petby = Dog.queryPetById(textBox12.Text);
                JObject petby_j = (JObject)JsonConvert.DeserializeObject(petby);
                string petby_ja = (string)petby_j["data"].ToString();
                AttributesData petby_OnSaleItem = (AttributesData)JsonConvert.DeserializeObject(petby_ja.ToString(), typeof(AttributesData));
                StringBuilder DograreDegree = new StringBuilder();
                StringBuilder DograreDegreep = new StringBuilder();
                for (int ia = 0; ia < petby_OnSaleItem.attributes.Count; ia++)
                {
                    //属性
                    if (petby_OnSaleItem.attributes[ia].rareDegree == "稀有")
                    {
                        DograreDegree.Append(petby_OnSaleItem.attributes[ia].name + ":" + petby_OnSaleItem.attributes[ia].value + ",  ");
                    }
                    else
                    {
                        DograreDegreep.Append(petby_OnSaleItem.attributes[ia].name + ":" + petby_OnSaleItem.attributes[ia].value + ",  ");
                    }
                }
                this.listView1.BeginUpdate();
                listView1.Items.Add(new ListViewItem(new string[] { petby_OnSaleItem.id.ToString(),
                        petby_OnSaleItem .amount.ToString(), petby_OnSaleItem .rareDegree.ToString(), petby_OnSaleItem .petId .ToString()
                        ,DograreDegree.ToString (),DograreDegreep.ToString (),"",petby_OnSaleItem.userName}));
                this.listView1.EndUpdate();

            }

        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GetMylist();
        }

        private void 刷新列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GetOaderlist();
        }

        private void 刷新用户信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Getuser();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Dispose(true);
            this.Close();
            Application.Exit();
        }
        public void GetpaeDog(int pages)
        {
            string ret = "";
            try
            {
                label12.Text = "第" + (pages).ToString() + "页";
                ret = Dog.queryPetsOnSale((pages).ToString(), "20", Getsort());
                JObject res_j = (JObject)JsonConvert.DeserializeObject(ret);
                JArray res_ja = (JArray)res_j["data"]["petsOnSale"];
                JObject apet = (JObject)res_ja[0];
                string apettt = res_ja.ToString();
                var arry = JsonConvert.DeserializeObject<object[]>(apettt);
                listView1.Items.Clear();
                textBox7.Text = "";
                string petid = (string)apet["petId"];
                string vcode = (string)apet["validCode"];
                string price_str = (string)apet["amount"];
                string birthType = Convert.ToString(apet["birthType"]);
                for (var i = 0; i < arry.Length; i++)
                {
                    List<AttributesItem> attri = new List<AttributesItem>();
                    StringBuilder DograreDegree = new StringBuilder();//稀有
                    StringBuilder DograreDegreep = new StringBuilder();//稀有
                    Postdata.PetsOnSaleItem PostOnSaleItem = (Postdata.PetsOnSaleItem)JsonConvert.DeserializeObject(arry[i].ToString(), typeof(Postdata.PetsOnSaleItem));
                    string petby = Dog.queryPetById(PostOnSaleItem.petId);
                    JObject petby_j = (JObject)JsonConvert.DeserializeObject(petby);
                    string petby_ja = (string)petby_j["data"].ToString();
                    AttributesData petby_OnSaleItem = (AttributesData)JsonConvert.DeserializeObject(petby_ja.ToString(), typeof(AttributesData));
                    if (checkBox4.Checked != true)
                    {
                        for (int ia = 0; ia < petby_OnSaleItem.attributes.Count; ia++)
                        {
                            //属性
                            if (petby_OnSaleItem.attributes[ia].rareDegree == "稀有")
                            {
                                DograreDegree.Append(petby_OnSaleItem.attributes[ia].name + ":" + petby_OnSaleItem.attributes[ia].value + ",  ");
                            }
                            else
                            {
                                DograreDegreep.Append(petby_OnSaleItem.attributes[ia].name + ":" + petby_OnSaleItem.attributes[ia].value + ",  ");
                            }
                        }
                        this.listView1.BeginUpdate();
                        listView1.Items.Add(new ListViewItem(new string[] { petby_OnSaleItem.id.ToString(),
                        petby_OnSaleItem .amount.ToString(), petby_OnSaleItem .rareDegree.ToString(), petby_OnSaleItem .petId .ToString()
                        ,DograreDegree.ToString (),DograreDegreep.ToString (),PostOnSaleItem.validCode,petby_OnSaleItem.userName}));
                        this.listView1.EndUpdate();

                    }
                }


            }
            catch (Exception)
            {
            }

        }
        private void buttshang_Click(object sender, EventArgs e)
        {
            if (Pages > 1)
            {
                GetpaeDog(Pages - 1);
            }
            else
            {
                GetpaeDog(Pages);
            }
        }
        private void button10_Click(object sender, EventArgs e)
        {
            if (Pages > 1)
            {
                GetpaeDog(Pages + 1);
            }
        }

        private void 抢狗模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            开始查询ToolStripMenuItem_Click(null, null);
        }

        private void 稳定模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripMenuItem1_Click(null, null);

        }

        private void comboBox4_SelectedIndexChanged_1(object sender, EventArgs e)
        {
           
            GetcookieTXT(comboBox4.Text );

        }

        private void 上一页ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            buttshang_Click(null,null);
        }

        private void 下一页ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (Pages > 1)
            {
                GetpaeDog(Pages + 1);
            }
        }

 
        private void comboBox4_Click(object sender, EventArgs e)
        {
            GetcookieTXT(comboBox4.Text);
        }

        private void 刷新狗库ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string sql = "select *from nameurl ";
            try
            {
                string dbPath = papa + "\\laicigou.db";
                SQLiteConnection conn = null;
               // string sql = "select * from nameurl where idname=" + idname;
                SQLiteDBHelper db = new SQLiteDBHelper(dbPath);

                //using (SQLiteDataReader reader = db.ExecuteReader(sql, null))
                //{
                //    dataGridView1.DataSource = reader;
                //}
             //   conn = new SQLiteConnection("Data Source =" + dbPath);
              //  conn.Open();

                //DataTable dt=

                DataTable da =db.ExecuteDataTable(sql,null);

                DataSet ds = new System.Data.DataSet();
                // da.Fill(ds, "idname");
                dataGridView2.DataSource = da;
               // dataGridView1.DataSource = ds.Tables[0];


            }
            catch (Exception)
            {


            }
            //    dataGridView1.DataSource =;
        }
    }
}
